package com.definity.toolkit.ui.widget;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;

import javax.swing.Icon;
import javax.swing.JFrame;
import javax.swing.JLabel;

import com.definity.toolkit.ToolkitRuntimeException;
import com.definity.toolkit.i18n.Config;
import com.definity.toolkit.ui.Body;
import com.definity.toolkit.ui.event.Event;
import com.definity.toolkit.ui.event.Observer;

public class Splash extends JFrame implements Observer, Widget<Splash> {

	private static final long serialVersionUID = -7495459769776064909L;
	
	private ProgressBar progressBar;

	private final WidgetBuilder b = new WidgetBuilder();
	
	private Splash(String title) {
		super(title);
		
		Container contentPane = getContentPane();
		contentPane.setLayout(new BorderLayout());
		
		try {
			Icon imageIcon = b.icon(Config.getProperty("image.logo"));
			JLabel image = new JLabel(imageIcon);
			contentPane.add(image, BorderLayout.CENTER);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		progressBar = b.progressBar().size(450, 20).indeterminate(true);
		contentPane.add(progressBar, BorderLayout.SOUTH);
		
		setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
		setSize(new Dimension(450, 300));
		setLocationRelativeTo(null);
		setAlwaysOnTop(true);
		setUndecorated(true);
		setVisible(true);
	}

	public static Splash display(String title) {
		return new Splash(title);
	}
	
	public void destroy() {
		super.dispose();
	}
	
	@Override
	@Deprecated
	public void dispose() {
		throw new ToolkitRuntimeException("Call destroy method");
	}

	@Override
	public void update(Event event) {
		int index = 0;
		
		if (index >= progressBar.getMaximum())
			destroy();
	}

	@Override
	public String id() {
		return getName();
	}

	@Override
	public Splash id(String id) {
		setName(id);
		return this;
	}

	@Override
	public Splash properties(Body<Splash> body) {
		body.content(this);
		return this;
	}

	@Override
	public Color background() {
		return getBackground();
	}

	@Override
	public Splash background(Color background) {
		setBackground(background);
		return this;
	}

	@Override
	public Color foreground() {
		return getForeground();
	}

	@Override
	public Splash foreground(Color foreground) {
		setForeground(foreground);
		return this;
	}

	@Override
	public Splash size(int width, int height) {
		setPreferredSize(new Dimension(width, height));
		return this;
	}

	@Override
	public Font font() {
		return getFont();
	}

	@Override
	public Splash font(Font font) {
		setFont(font);
		return this;
	}
	
}
